package me.spring.cloud.common.components.jest.page;

import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author luffy
 * @date 2019-10-11 09:44
 */
@Data
@NoArgsConstructor
public class EsSimplePage implements EsPaginable {

  private static final long serialVersionUID = 8923946017098615943L;

  public static final int DEF_COUNT = 20;

  protected int totalCount = 0;
  protected int pageSize = 20;
  protected int pageNo = 1;
  protected int filterNo;

  public EsSimplePage(int pageNo, int pageSize, int totalCount) {
    if (totalCount <= 0) {
      this.totalCount = 0;
    } else {
      this.totalCount = totalCount;
    }
    if (pageSize <= 0) {
      this.pageSize = DEF_COUNT;
    } else {
      this.pageSize = pageSize;
    }
    if (pageNo <= 0) {
      this.pageNo = 1;
    } else {
      this.pageNo = pageNo;
    }
    if ((this.pageNo - 1) * this.pageSize >= totalCount) {
      this.pageNo = totalCount / pageSize;
      if (this.pageNo == 0) {
        this.pageNo = 1;
      }
    }
  }

  /**
   * 调整分页参数，使合理化
   */
  public void adjustPage() {
    if (totalCount <= 0) {
      totalCount = 0;
    }
    if (pageSize <= 0) {
      pageSize = DEF_COUNT;
    }
    if (pageNo <= 0) {
      pageNo = 1;
    }
    if ((pageNo - 1) * pageSize >= totalCount) {
      pageNo = totalCount / pageSize;
    }
  }

  @Override
  public int getTotalPage() {
    int totalPage = totalCount / pageSize;
    if (totalCount % pageSize != 0 || totalPage == 0) {
      totalPage++;
    }
    return totalPage;
  }

  @Override
  public boolean isFirstPage() {
    return pageNo <= 1;
  }

  @Override
  public boolean isLastPage() {
    return pageNo >= getTotalPage();
  }

  @Override
  public int getNextPage() {
    if (isLastPage()) {
      return pageNo;
    } else {
      return pageNo + 1;
    }
  }

  @Override
  public int getPrePage() {
    if (isFirstPage()) {
      return pageNo;
    } else {
      return pageNo - 1;
    }
  }
}
